<template>
  <div class="qr">
    <canvas ref="qrcodeCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import QRCode from "qrcode"

// 定义 props
const props = defineProps({
  url: {
    type: String,
    required: true,
  },
  size: {
    type: Number,
    default: 360,
  },
})

// 引入图片资源
import logoImg from '@/assets/common/logo.png'

// 响应式数据
const logo = ref(logoImg)
const logoScale = ref(0.15)

// DOM引用
const qrcodeCanvas = ref(null)

// 方法定义
const generateQRCode = async () => {
  try {
    const canvas = qrcodeCanvas.value
    if (!canvas) return

    const ctx = canvas.getContext("2d")
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    await QRCode.toCanvas(canvas, props.url, {
      width: props.size,
      margin: 2,
      errorCorrectionLevel: "H",
    })

    const logoImg = new Image()
    logoImg.src = logo.value
    logoImg.onload = () => {
      const logoSize = canvas.width / 4
      const x = (canvas.width - logoSize) / 2
      const y = (canvas.height - logoSize) / 2

      // 绘制白色背景
      ctx.fillStyle = "#ffffff"
      ctx.fillRect(x - 5, y - 5, logoSize + 10, logoSize + 10)

      // 绘制Logo
      ctx.drawImage(logoImg, x, y, logoSize, logoSize)
    }
  } catch (error) {
    console.error("生成失败:", error)
  }
}

// 监听 url 变化，重新生成二维码
watch(() => props.url, () => {
  generateQRCode()
})

// 生命周期钩子
onMounted(() => {
  generateQRCode()
})

// 定义暴露给父组件的方法
defineExpose({
  generateQRCode
})
</script>

<style lang="less" scoped>
.qr {
  padding: 3px;
  width: 147px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 7px;
  display: flex;
  align-items: center;
  justify-content: center;

  canvas {
    max-width: 100%;
    height: auto !important;
    user-select: none;
  }
}
</style>
